package com.dm.cloud.utils.entity;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.dm.cloud.annotions.FieldResponedNullable;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Log4j2
public class EntityUtils {

    /**
     * 移除实体类中为null的字段
     * @param entity
     * @return
     */
    public static<T>  Object removeNullField(T entity) {

        Map<String,Object> result = new LinkedHashMap<>();

        //遍历实体类中的字段
        try {
            Class cls = entity.getClass();
            //类上添加该注解 表示整个类中的字段都可以返回null 否则要校验字段上有没有该注解
            FieldResponedNullable clsFieldNullable = AnnotationUtils.findAnnotation(cls, FieldResponedNullable.class);
            if(clsFieldNullable == null){
                Field[] fields = cls.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    Field f = fields[i];
                    FieldResponedNullable fieldNullable = AnnotationUtils.findAnnotation(f, FieldResponedNullable.class);
                    //字段上没有该注解 返回非null属性
                    if(fieldNullable == null){
                        f.setAccessible(true);
                        //判断是否为NULL
                        if (ObjectUtils.isNotNull(f.get(entity))) {
                            result.put(f.getName(), f.get(entity));
                        }
                    }else{
                        f.setAccessible(true);
                        result.put(f.getName(), f.get(entity));
                    }
                }
            }else{
                return entity;
            }

        }catch (Exception ex){
           log.warn("实体类字段整理异常",ex.getCause());
        }

        //serialVersionUID 有值也不返回
        result.remove("serialVersionUID");

        return result;
    }
}
